package com.dreamsky.life;

import com.dreamsky.life.controller.ElectricController;
import com.dreamsky.life.controller.LifeController;
import com.dreamsky.life.controller.LoginController;
import com.dreamsky.life.model.*;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.dialect.Sqlite3Dialect;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.jfinal.render.ViewType;

public class LifeConfig extends JFinalConfig {

	@Override
	public void configConstant(Constants me) {
		me.setDevMode(true);
		me.setViewType(ViewType.JSP);

	}

	@Override
	public void configHandler(Handlers me) {
		// TODO Auto-generated method stub

	}

	@Override
	public void configInterceptor(Interceptors me) {
		// TODO Auto-generated method stub

	}

	@Override
	public void configPlugin(Plugins me) {
		// loadPropertyFile("db.properties");
		boolean isLocal = false;

		C3p0Plugin cp = new C3p0Plugin(getMysqlURL(isLocal), userName(isLocal),
				password(isLocal));
		// cp.setDriverClass(getProperty("driverClass"));
		ActiveRecordPlugin arp = new ActiveRecordPlugin(cp);
		arp.setContainerFactory(new CaseInsensitiveContainerFactory(true));
		// arp.setDialect(new Sqlite3Dialect());

		arp.addMapping("lf_user", User.class);
		arp.addMapping("lf_electric", Electric.class);
		arp.addMapping("lf_ele_con", ElectricContinuous.class);
		arp.addMapping("lf_ele_control", ElectricControl.class);
		arp.addMapping("lf_ele_resume", ElectricResume.class);
		arp.addMapping("lf_ele_task", ElectricTask.class);
		arp.addMapping("lf_ele_type", ElectricType.class);

		me.add(cp);
		me.add(arp);
	}

	@Override
	public void configRoute(Routes me) {
		me.add("/", LoginController.class);
		me.add("/light", LifeController.class);
		me.add("/electric", ElectricController.class);
	}

	private String getMysqlURL(boolean isLocal) {
		return isLocal ? getLoacalMysqlURL() : getCloudMysqlURL();
	}

	private String getLoacalMysqlURL() {
		return "jdbc:mysql://127.0.0.1:3306/life";
	}

	private String getCloudMysqlURL() {
		String ip = System.getenv("MOPAAS_MYSQL4641_HOST");
		String dbName = System.getenv("MOPAAS_MYSQL4641_NAME");
		String port = System.getenv("MOPAAS_MYSQL4641_PORT");

		return "jdbc:mysql://" + ip + ":" + port + "/" + dbName;
	}

	private String userName(boolean isLocal) {
		return isLocal ? "root" : System.getenv("MOPAAS_MYSQL4641_USERNAME");

	}

	private String password(boolean isLocal) {
		return isLocal ? "mysql_coxon" : System
				.getenv("MOPAAS_MYSQL4641_PASSWORD");
	}
}
